<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2020/8/5
 * Time: 9:39
 */
namespace app\api\controller;
use think\Db;
class Notice extends Base {
    public function __construct()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
    }
    //消息列表
    public function index(){
        extract(input());
        $page = input('param.page')?input('param.page'):1;
        $num = 10;
        $limit = ($page-1)*$num;
        $type = input('param.type')?input('param.type'):1;
        if($type==1){//订单消息
            $where['n_notice_type'] = 2;
            $where['n_user_id'] = ['like', '%,' . $user_id . ',%'];
            $list = Db::table('up_notice')
                ->where($where)
                ->order('n_time desc')
                ->limit($limit,$num)
                ->select();
        }elseif ($type==2){//系统消息
            $where['n_notice_type'] = 1;
            $where['n_type'] = 1;
//            $where['n_user_id'] = ['like', '%,' . $user_id . ',%'];
            $list = Db::table('up_notice')
                ->where($where)
                ->whereOr('n_type',1)
                ->order('n_time desc')
                ->limit($limit,$num)
                ->select();
        }

        if($list){
            foreach($list as $k => $v){
                // 已读/未读
                $read_user = explode(',', trim($v['n_read'], ','));
                if(in_array($user_id, $read_user)){
                    $list[$k]['is_read'] = 1; // 已读
                }else{
                    $list[$k]['is_read'] = 2; // 未读
                }
            }
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 系统消息详情 同时修改已读/未读状态
     * @return \think\response\Json
     * n_id   消息ID
     */
    public function noticeDetail(){
        extract(input());
        $n_id = input('n_id');
        $detail = Db::table('up_notice')
            ->field('n_title, n_content, n_read')
            ->where('n_id', $n_id)
            ->find();
        if($detail){
            // 是否是已读消息
            $is_read = explode(',', trim($detail['n_read'], ','));
            if(!in_array($user_id, $is_read)){ // 不在已读数组中，说明未读，需要加入已读字段
                $read_user = $detail['n_read'] .$user_id . ',';
                Db::table('up_notice')->where('n_id', $n_id)->setField('n_read', $read_user);
            }
            return json(['status' => 200, 'msg' => $detail]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

}